package com.fang.config.security;

import com.fang.common.cache.RedisCacheEnum;
import com.fang.common.exception.CaptchaException;
import com.fang.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Fang Ruichuan
 * @date 2022-08-31 21:58
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = request.getRequestURI();
        if (StringUtils.equals("/login", url) && request.getMethod().equals("POST")) {
            try {
                // 校验验证码
                validate(request);
            } catch (CaptchaException e) {
                // 交给认证失败处理器
                loginFailureHandler.onAuthenticationFailure(request, response, e);
            }
        }
        filterChain.doFilter(request, response);
    }

    // 校验验证码逻辑
    private void validate(HttpServletRequest request) {
        String code = request.getParameter("code");
        String key = request.getParameter("token");
        if (StringUtils.isBlank(code) || StringUtils.isBlank(key)) {
            throw new CaptchaException("验证码错误");
        }
        if (!StringUtils.equals(code, RedisUtil.StringOps.get(RedisCacheEnum.CAPTCHA_KEY.getValue() + ":" + key))) {
            throw new CaptchaException("验证码错误");
        }
        RedisUtil.KeyOps.delete(RedisCacheEnum.CAPTCHA_KEY.getValue() + ":" + key);
    }
}
